package com.ukit.weather_xml

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.ukit.weather_xml.Other.DataManger.Cityes.CityAdapter
import com.ukit.weather_xml.Other.DataManger.Settings
import com.ukit.weather_xml.Other.DataManger.SettingsApp
import com.ukit.weather_xml.Other.DataManger.WeatherDao
import com.ukit.weather_xml.Other.DataManger.WeatherDatabase
import com.ukit.weather_xml.Other.DataManger.UserCity
import com.ukit.weather_xml.databinding.ActivityChangeCityBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ChangeCityActivity : AppCompatActivity(), CityAdapter.OnCityClickListener {

    private lateinit var binding: ActivityChangeCityBinding
    private lateinit var adapter: CityAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChangeCityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        adapter = CityAdapter(emptyList(), this)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter

        binding.pushCity.setOnClickListener {
            val newCity = binding.inputCity.text.toString()
            GlobalScope.launch(Dispatchers.IO) {
                SettingsApp.weatherDao.insertUserCity(UserCity(city = newCity))
                val cities = SettingsApp.weatherDao.getUserCities()
                withContext(Dispatchers.Main) {
                    adapter.setData(cities)
                }
            }
        }

        loadCitiesFromDatabase()
    }

    private fun loadCitiesFromDatabase() {
        GlobalScope.launch(Dispatchers.IO) {
            val cities = SettingsApp.weatherDao.getUserCities()
            withContext(Dispatchers.Main) {
                adapter.clearData()
                adapter.setData(cities)
            }
        }
    }


    override fun onCityClick(city: UserCity) {
        GlobalScope.launch(Dispatchers.IO) {
            Log.e("c", city.city)
            SettingsApp.settingsDao.updateCity(city.city)
            SettingsApp.settingsDao.getSettings()!!.forEach{
                Log.e("F", it.city)
            }
            withContext(Dispatchers.Main) {
                val resultIntent = Intent()
                setResult(Activity.RESULT_OK, resultIntent)
                finish()
            }
        }
    }


    companion object {
        fun newIntent(context: Context): Intent {
            return Intent(context, ChangeCityActivity::class.java)
        }
    }
}
